package com.xuwangcheng.springboot.common.validate;

import cn.hutool.core.collection.CollUtil;
import com.xuwangcheng.springboot.common.exception.AppErrorCode;
import com.xuwangcheng.springboot.common.exception.AppException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * hibernate-validator校验
 * @author xuwangcheng
 * @version 1.0.0
 * @description
 * @date 2020/4/29 17:09
 */
public class ValidateUtil<T> {
    private static Validator validator;

    static {
        /**
         * 使用hibernate的注解来进行验证 failFast true仅仅返回第一条错误信息 false返回所有错误
         */
        validator = Validation
                .byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
    }

    /**
     * 手动校验
     * @param obj 校验的对象
     * @param <T>
     * @return
     */
    public static <T> void validate(T obj, Class... groupClasses) {
        Set<ConstraintViolation<T>> constraintViolations;
        if(groupClasses != null && groupClasses.length > 0){
            constraintViolations = validator.validate(obj, groupClasses);
        }else {
            constraintViolations = validator.validate(obj);
        }
        if (CollUtil.isNotEmpty(constraintViolations)) {
            throw new AppException(AppErrorCode.INVALID_PARAMETER, constraintViolations.iterator().next().getMessage());
        }
    }
}
